#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------
# Author:  LJ
# Email:   admin@attacker.club

# Last Modified: 2018-06-19 21:38:35
# Description:  Py3
# --------------------------------------
 
import re,time,datetime
import paramiko



DEBUG =  True#False 




cmdlist = [
"ftp.conf 36.27.209.76",
"ftpcenter",
"ftppass",
"cd net_config"
]


def run(host):
    now = datetime.datetime.now()
    today = now.strftime('%Y%m%d')
    logdate = now.strftime("%b %d %H:%M:%S")
    #paramiko.util.log_to_file('paramiko.log')
    print("INFO:\t%s\t[\033[1;32m%s\033[0m] Trying to connect　..." % (logdate, host))

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(
            hostname=host,
            username=user,
            password=passwd,
            port=55556,
            pkey=None, look_for_keys=False,
            timeout=3, allow_agent=False)

        remote_conn = ssh.invoke_shell()
        time.sleep(0.1) # 设置间隔
        print(remote_conn.recv(1000).decode())




        for cmdline in cmdlist:
            remote_conn.send("%s\n" % cmdline)
            time.sleep(0.5)


        output = remote_conn.recv(1000).decode()
        devname = re.findall(r'\<(.*)\>.*',output)[0] #正则导入主机名
        remote_conn.send("put startup.cfg %s-%s-%s.cfg\n" % (devname,host,today))
        time.sleep(2)
        #remote_conn.send("rename startup.cfg %s-%s.cfg-%s\n" % (devname,host,today))
        print(remote_conn.recv(1000).decode())
        time.sleep(0.1)
        remote_conn.send("quit\n")
        time.sleep(0.1)



        remote_conn.send('save\n')  #保存设备当前配置
        time.sleep(0.5)
        save = remote_conn.recv(1000).decode()
        if save.find('written') > -1:
            remote_conn.send("Y\n")
            time.sleep(1)
            remote_conn.send("\n")
            remote_conn.send("Y\n")
            # time.sleep(5)
            #print(remote_conn.recv(1000))

    except Exception as e:
        print(e, type(e))
    finally:
        ssh.close()
        print("INFO:\t%s\t[\033[1;32m%s\033[0m] Execute successfully　..." % (logdate, host))


        




if __name__ == '__main__':
    user = 'admin'
    passwd = input("输入密码: ")

    if not DEBUG:
        with open("host.txt") as f:
            for host in f:
                run(host)
    else:
        run('122.225.68.107') #测试

